package com.yan_jiu_sheng.LeetCodeHot100.AC;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * https://leetcode.cn/problems/two-sum/?envType=study-plan-v2&envId=top-100-liked
 * 通过
 *
 * @author yulongTian
 * @create 2024-05-23 20:54
 */
public class Test01 {

    public static void main(String[] args) {
        int[] nums = {3, 2, 4};
        /*
        2   0
        7   1
        11  2
        15  3
         */
        int target = 6;
        System.out.println(Arrays.toString(twoSum(nums, target)));
    }

    public static int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        HashMap<Integer, ArrayList<Integer>> hashMap = new HashMap<>();
        // 0 自己 1 没有 2 已找到
        for (int i = 0; i < nums.length; i++) {
            if (hashMap.isEmpty()) {
                ArrayList<Integer> temp = new ArrayList<>();
                temp.add(i);
                hashMap.put(nums[i], temp);
                continue;
            }
            if (hashMap.containsKey(nums[i])) {
                hashMap.get(nums[i]).add(i);
            } else {
                ArrayList<Integer> temp = new ArrayList<>();
                temp.add(i);
                hashMap.put(nums[i], temp);
            }
        }
        for (int i = 0; i < nums.length; i++) {
            // 相等
            if (target - nums[i] == nums[i]) {
                if (hashMap.containsKey(nums[i]) && hashMap.get(nums[i]).size() >= 2) {
                    res[0] = i;
                    res[1] = hashMap.get(nums[i]).get(0);
                }
            } else {
                if (hashMap.containsKey(target - nums[i])) {
                    res[0] = i;
                    res[1] = hashMap.get(target - nums[i]).get(0);
                    break;
                }
            }
        }
        return res;
    }

}
